﻿using System;
using System.Net.Mail;
using System.Windows.Forms;
using System.IO;

namespace SendMailIPCC
{
    public partial class frmMain : Form
    {
        private System.Windows.Forms.OpenFileDialog ofd;
        string File1;
        string File2;
        string File3;
        string File4;
        string File5;
        private bool invalid;
        string path;
        private NotifyIcon notifyIcon;
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnFile1_Click(object sender, EventArgs e)
        {
            SelectFile(File1, txtFile1);
        }

        private void SelectFile(string File, TextBox txt)
        {
            ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txt.Text = File = ofd.FileName;
            }
        }
        private bool IsValidEmailAddress(string EmailAddress)
        {
            string strPattern = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
            if (System.Text.RegularExpressions.Regex.IsMatch(EmailAddress, strPattern))
                return true;
            return false;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {

            try
            {
                string[] arrTo = txtTo.Text.Trim().Split(';', ',', ' ');
                string[] arrCc = txtCc.Text.Trim().Split(';', ',', ' ');
                string[] arrBcc = txtBcc.Text.Trim().Split(';', ',', ' ');
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(txtHost.Text.Trim());
                mail.From = new MailAddress(txtUser.Text.Trim());

                foreach (var item in arrTo)
                {
                    if (item.Trim().Length != 0)
                    {
                        if (!IsValidEmailAddress(item.Trim()))
                        {
                            MessageBox.Show(item + " không đúng định dạng của 1 email, vui lòngkiểm tra lại.",
                                "Lỗi định dạng", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                            mail.To.Add(item);
                    }
                }
                foreach (var item in arrCc)
                {
                    if (item.Trim().Length != 0)
                    {
                        if (!IsValidEmailAddress(item.Trim()))
                        {
                            MessageBox.Show(item + " không đúng định dạng của 1 email, vui lòngkiểm tra lại.",
                                "Lỗi định dạng", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                            mail.CC.Add(item);
                    }
                }
                foreach (var item in arrBcc)
                {
                    if (item.Trim().Length != 0)
                    {
                        if (!IsValidEmailAddress(item.Trim()))
                        {
                            MessageBox.Show(item + " không đúng định dạng của 1 email, vui lòngkiểm tra lại.",
                                "Lỗi định dạng", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        else
                            mail.Bcc.Add(item);
                    }
                }
                mail.Subject = txtSub.Text.Trim();
                mail.Body = txtBody.Text.Trim();
                try
                {
                    if (System.IO.File.Exists(txtFile1.Text.Trim()))
                    {
                        Attachment attachment = new System.Net.Mail.Attachment(txtFile1.Text.Trim());
                        mail.Attachments.Add(attachment);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("6 " + ex.ToString());
                }
                try
                {
                    if (System.IO.File.Exists(txtFile2.Text.Trim()))
                    {
                        Attachment attachment = new System.Net.Mail.Attachment(txtFile2.Text.Trim());
                        mail.Attachments.Add(attachment);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("5 " + ex.ToString());
                }
                try
                {
                    if (System.IO.File.Exists(txtFile3.Text.Trim()))
                    {
                        Attachment attachment = new System.Net.Mail.Attachment(txtFile3.Text.Trim());
                        mail.Attachments.Add(attachment);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("4 " + ex.ToString());
                }
                try
                {
                    if (System.IO.File.Exists(txtFile4.Text.Trim()))
                    {
                        Attachment attachment = new System.Net.Mail.Attachment(txtFile4.Text.Trim());
                        mail.Attachments.Add(attachment);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("3 " + ex.ToString());
                }
                try
                {
                    if (System.IO.File.Exists(txtFile5.Text.Trim()))
                    {
                        Attachment attachment = new System.Net.Mail.Attachment(txtFile5.Text.Trim());
                        mail.Attachments.Add(attachment);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("2 " + ex.ToString());
                }

                SmtpServer.Port = Int32.Parse(txtPort.Text.Trim());
                string[] user = txtUser.Text.Trim().Split('@');
                SmtpServer.EnableSsl = true;
                SmtpServer.Credentials = new System.Net.NetworkCredential(user[0], txtPass.Text);
                SmtpServer.EnableSsl = true;
                SmtpServer.Timeout = 2000000;
                Hide();
                nf.Visible = true;
                nf.ShowBalloonTip(500);
                SmtpServer.Send(mail);
                nf.Visible = false;
                this.Show();
                MessageBox.Show("Đã gởi thành công...",
                   "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("1 " + ex.ToString());
            }
        }
        

        private void btnFile2_Click(object sender, EventArgs e)
        {
            SelectFile(File2, txtFile2);
        }

        private void btnFile3_Click(object sender, EventArgs e)
        {
            SelectFile(File3, txtFile3);
        }

        private void btnFile4_Click(object sender, EventArgs e)
        {
            SelectFile(File4, txtFile4);
        }

        private void btnFile5_Click(object sender, EventArgs e)
        {
            SelectFile(File5, txtFile5);
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn chắc chắn muốn thoát?", "Xác nhận", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                Application.Exit();
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            Text = "Mail Program IPCC - mrvandai -:|:- " + DateTime.Now.ToShortDateString() + " - " + DateTime.Now.ToShortTimeString();
            LoadToEmail();
            LoadCcEmail();
            LoadBccEmail();
        }

        private void LoadToEmail()
        {
            path = Directory.GetCurrentDirectory().ToString();
            try
            {
                using (StreamReader objReader = new StreamReader(path + @"\ToEmail.txt"))
                {
                    txtTo.Text = "";
                    do
                    {
                        string email = objReader.ReadLine() + ", ";
                        if (email.Substring(0, email.Length - 2).Trim().Length > 4)
                        {
                            txtTo.Text += email;
                        }
                    } while (objReader.Peek() != -1);
                    txtTo.Text = txtTo.Text.Substring(0, txtTo.Text.Length - 2);
                }
            }
            catch
            {
            }
        }
        private void LoadBccEmail()
        {
            path = Directory.GetCurrentDirectory().ToString();
            try
            {
                using (StreamReader objReader = new StreamReader(path + @"\BccEmail.txt"))
                {
                    txtBcc.Text = "";
                    do
                    {
                        string email = objReader.ReadLine() + ", ";
                        if (email.Substring(0, email.Length - 2).Trim().Length > 4)
                        {
                            txtBcc.Text += email;
                        }
                    } while (objReader.Peek() != -1);
                    txtBcc.Text = txtBcc.Text.Substring(0, txtBcc.Text.Length - 2);
                }
            }
            catch
            {
            }
        }
        private void LoadCcEmail()
        {
            path = Directory.GetCurrentDirectory().ToString();
            try
            {
                using (StreamReader objReader = new StreamReader(path + @"\CcEmail.txt"))
                {
                    txtCc.Text = "";
                    do
                    {
                        string email = objReader.ReadLine() + ", ";
                        if (email.Substring(0, email.Length - 2).Trim().Length > 4)
                        {
                            txtCc.Text += email;
                        }
                    } while (objReader.Peek() != -1);
                    txtCc.Text = txtCc.Text.Substring(0, txtCc.Text.Length - 2);
                }
            }
            catch
            {
            }
        }

        private void btnF5To_Click(object sender, EventArgs e)
        {
            LoadToEmail();
        }

        private void btnF5Cc_Click(object sender, EventArgs e)
        {
            LoadCcEmail();
        }

        private void btnF5Bcc_Click(object sender, EventArgs e)
        {
            LoadBccEmail();
        }

        private void btnLuuTo_Click(object sender, EventArgs e)
        {
            string[] arr = txtTo.Text.Trim().Split(';', ',', ' ');
            using (StreamWriter newTask = new StreamWriter("ToEmail.txt", false))
            {
                foreach (var item in arr)
                {
                    newTask.WriteLine(item);
                }
                newTask.Close();
            }
        }

        private void btnLuuCc_Click(object sender, EventArgs e)
        {
            string[] arr = txtCc.Text.Trim().Split(';', ',', ' ');
            using (StreamWriter newTask = new StreamWriter("CcEmail.txt", false))
            {
                foreach (var item in arr)
                {
                    newTask.WriteLine(item);
                }
                newTask.Close();
            }
        }

        private void btnLuuBcc_Click(object sender, EventArgs e)
        {
            string[] arr = txtBcc.Text.Trim().Split(';', ',', ' ');
            using (StreamWriter newTask = new StreamWriter("BccEmail.txt", false))
            {
                foreach (var item in arr)
                {
                    newTask.WriteLine(item);
                }
                newTask.Close();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Text = "Mail Program IPCC - mrvandai -:|:- " + DateTime.Now.ToShortDateString() + " - " + DateTime.Now.ToShortTimeString();
        }

        private void frmMain_Resize(object sender, EventArgs e)
        {

        }

        private void nf_DoubleClick(object sender, EventArgs e)
        {
            nf.ShowBalloonTip(200);
        }
    }
}
